<script setup lang="ts">
import { ref } from 'vue'
import io from 'socket.io-client'
import { getNewStream } from './utils.js'
import UserList from './UserList.vue';

const videoA = ref<HTMLVideoElement>() as any
const videoB = ref<HTMLVideoElement>() as any

let userList = ref(<any>[])
let iptuserName = ref('')
let userName = ref('')
let targetName = ref('')
let offer = ref(null) as any
let answer = null as any
let stream = null as any


var peer = new RTCPeerConnection()


  // 检测连接状态
  peer.onconnectionstatechange = () => {
    if (peer.connectionState === 'connected') {
      console.log('对等连接成功！')
    }
  }
  // 监听数据传来
  peer.ontrack = async event => {
    const [remoteStream] = event.streams
    videoB.value.srcObject = remoteStream
  }

  // 添加 candidate



  const socket = io('https://192.168.10.123:3000')

  socket.on('system',async (data,event)=>{
    switch (event) {
      case 'login':
        let idx = userList.value.findIndex((i:any) => i.userName === data.userName)
        
        idx < 0 && userList.value.push({userName:data.userName})
        break;
      case 'offer':
        if(data.userName === userName.value ){
          console.log('offer',data);
          offer.value = data.offer
          targetName.value = data.offerName
        }
        break;
      case 'answer':
        console.log(data.userName, userName.value);
        
        if(data.userName === userName.value ){
          console.log('answer');
          answer = data.answer
          await peer.setLocalDescription(offer.value)
          await peer.setRemoteDescription(answer)
          videoA.value.srcObject = stream
        }
        break;
      case 'candidate':
        if(data.userName === userName.value ){
          console.log('candidate');
          peer.addIceCandidate(data.candidate)
        }
        break;
      case 'userlist':
        userList.value = data.userList
        break;
      default:
        break;
    }
  })


  const send = async ()=>{
    if (!targetName.value){
      return alert('未选择用户')
    }
    
    stream = await getNewStream()
    // videoA.value.srcObject = stream
    // 2. 添加视频流轨道
    stream.getTracks().forEach((track:any) => {
      peer.addTrack(track, stream)
    })

    offer.value = await peer.createOffer()
    
    socket.emit('offer', { userName: targetName.value, offerName: userName.value,  offer:offer.value })

    peer.onicecandidate = event => {
    if (event.candidate) {
      // peer.addIceCandidate(event.candidate)
      socket.emit('candidate',{userName:targetName.value,candidate:event.candidate})
    }
  }
  }

  const receive = async ()=>{
      console.log(offer.value);
      
      let stream = await getNewStream()
      videoA.value.srcObject = stream
      // 2. 添加视频流轨道
      stream.getTracks().forEach((track:any) => {
        peer.addTrack(track, stream)
      })
      await peer.setRemoteDescription(offer.value)
      // 2. 创建 answer
      answer = await peer.createAnswer(offer.value)
      await peer.setLocalDescription(answer)

      socket.emit('answer',{userName:targetName.value,answer})

    }
  
  // const choose = (name:any)=>{
  //   targetName.value = name
  // }
  const login = ()=>{
    userName.value = iptuserName.value
    socket.emit('login',{userName:userName.value})
  }
</script>

<template>
  <div class="chat_page">
    <header>
      <h1>聊天室</h1>
      <!-- <div v-if="userName" class="username">
        <span>用户名:  {{ userName }}</span>
      </div> -->
      <div class="login" >
        <CellGroup >
          <Field v-model="iptuserName"  center clearable label="用户名" placeholder="请输入用户名" >
          <template #button>
            <Button  @click="login">登录</Button>
          </template>
        </Field>
      </CellGroup>
    </div>
  </header>
  <div class="chat">
    <UserList class="userlist" v-model:targetName="targetName"  :user-list="userList"></UserList>
    <div class="videochat">
      <div class="client left">
        <video v-show="offer"  ref="videoA" autoplay controls></video>
        <Button plain type="default" @click="send()">拨打</Button>
      </div>
      <div v-show="offer" class="client right">
        <video ref="videoB" autoplay controls></video>
        <Button  :style="{color: targetName ? 'red':'black'}" @click="receive">接听</Button>
      </div>
    </div>

  </div>
  </div>
</template>

<style scoped>
.chat_page{
  width: 100%;
}
.chat{
  display: flex;
  width: 100%;
  justify-content: space-between;
}
.userlist{
  flex: 1;
  background-color: rgba(138, 136, 136, 0.274);
}
.videochat{
  display: flex;
  flex: 3;
  border-left: 1px solid rgb(204, 204, 204);
  background-color: rgba(224, 224, 224, 0.568);
}
.client{
  display: flex;
  flex-direction: column;
  align-items: center;
}
.client button{
  width: max-content;
}

.username{
  display: flex;
  justify-content: flex-end;
}

</style>
